<?php
/**
 * 广告平台基础控制器
 *
 * @author liang<lang@vip.deyi.com>
 * @since   2016/12/17 11:24
 * @copyright  deyi.com
 */

namespace Apps\Common\Controller;

use Apps\Acp\Models\ManagerLog;
use Apps\Acp\Services\ManagerGroupService;
use Apps\Common\Constant\AcpConstant;
use Apps\Common\Constant\ExceptionConstant;
use Deyi\Functions\UtilFunction;

/**
 * Class AcpBaseController
 * @package Apps\Common\Controller
 */
class AcpBaseController extends BaseController
{
    public static $nowModule = '首页';

    public static $nowAction = '';

    public $controlerName = '';

    public $actionName = '';

    public $curNavLink = '';

    public static $privileges = [];

    protected static $userSession = null;

    public function initialize()
    {
        parent::initialize();

        $this->controlerName = strtolower($this->dispatcher->getControllerName());
        $this->actionName = strtolower($this->dispatcher->getActionName());

        // 权限判断
        static::$userSession = $this->session->get(AcpConstant::MANAGER_SESSION);

        if (!static::$userSession && !in_array($this->controlerName . '/' . $this->actionName, ['account/login', 'account/logging', 'account/captcha'])
        ) {
            if ($this->request->isAjax()) {
                static::errorThrow('登录状态失效');
            } else {
                $this->redirectToUrl('/acp/login');
            }
        }

        //权限检查
        if (isset(static::$userSession->groupid)) {
            static::$privileges = ManagerGroupService::getInstance()->getPrivilegesByGid(static::$userSession->groupid);
        }
        static::$privileges[] = 'index'; // 首页所有人都可以访问
        static::$privileges[] = 'account';
        static::$privileges[] = 'common';
        static::$privileges[] = 'campaign';
        static::$privileges[] = 'business';
        static::$privileges[] = 'goods';
        static::$privileges[] = 'share';
        static::$privileges[] = 'order';
        static::$privileges[] = 'gift';
        static::$privileges[] = 'apply';
        static::$privileges[] = 'refund';
        static::$privileges[] = 'trade';
        if (!in_array($this->controlerName, static::$privileges)) {
            static::errorThrow('你无权访问此页面');
        }

        //操作日志记录
        if ($this->request->isPost()) {
            $postData = json_encode($this->request->getPost(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            $log = <<<EOF
访问地址:
{$this->request->getURI()}
提交的数据:
{$postData}
EOF;

            ManagerLog::getInstance()->record(
                isset(static::$userSession->id) ? static::$userSession->id : 0,
                UtilFunction::getClientIp(),
                $log
            );
        }

        //开启前端视图渲染
        $this->view->enable();

        $this->view->setVars(
            [
                'static_res_version' => static::$_config->project->staticversion,
                'sidenav' => $this->getSideNav(),
                'activeurl' => strtolower($this->dispatcher->getControllerName()),
                'nowmodule' => static::$nowModule,
                'nowaction' => static::$nowAction,
                'navlink' => $this->curNavLink,
                'account_username' => isset(static::$userSession->username) ? static::$userSession->username : '',
                'errormsg' => $this->getThrowError(),
            ]
        );

    }


    private function getSideNav()
    {
        $allow = AcpConstant::MODULES;

        foreach (AcpConstant::MODULES as $m => $arr) {
            foreach ($arr as $k => $v) {
                if ($k == $this->controlerName) {
                    static::$nowModule = $m;
                    static::$nowAction = $v;
                    $this->curNavLink = $k;
                }

                if (!in_array($k, static::$privileges)) {
                   unset($allow[$m][$k]);
                }
            }

            if(count($allow[$m]) == 0) {
                unset($allow[$m]);
            }
        }
        return $allow;
    }

    protected function getParamValue($fieldName, $defaultValue = null, $forceType = null, $get = false, $error = '', $redirect = false)
    {
        $v = $this->request->get($fieldName);
        $value = (isset($v) && '' !== $v) ? $v : null;

        //特殊的 闭包 处理方式
        if ($defaultValue instanceof \Closure) {
            $retValue = $defaultValue($value);
            if (isset($retValue)) {
                $value = $retValue;
            }
        } else {
            $value = (null === $value) ? $defaultValue : $value;
        }

        if ($value !== 0 && $value !== '0' && empty($value) && is_null($defaultValue)) {

            if ($redirect) {
                $this->flashSession->error($error ? $error : ($fieldName . '参数为空'));
                header('Location: ' . $this->request->getHTTPReferer());
                exit();
            }

            throw new \Exception($error ? $error : ($fieldName . '参数为空'), ExceptionConstant::PARAMS_EMPTY);
        }

        if (is_null($forceType)) {
            return $value;
        }

        switch ($forceType) {
            case 'int':
                return (int)$value;
            case 'float':
                return (float)$value;
            case 'double':
                return (double)$value;
            case 'boolean':
                return (bool)$value;
            default:
                return $value;
        }

    }

    public function returnPrevious($redirect = '')
    {
        $this->redirectToUrl($redirect ? $redirect : $this->request->getHTTPReferer());
    }

    /**
     * 抛出错误
     *
     * @author liang<lang@vip.deyi.com>
     * @param $msg
     * @param int $errorCode
     * @param bool $redirect
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function throwError($msg, $errorCode = ExceptionConstant::INTERNAL_ERROR, $redirect = true)
    {
        if ($redirect && static::$userSession) {
            $this->flashSession->error($msg);
            $this->returnPrevious();
        }

        static::errorThrow($msg, $errorCode);
    }

    public function getThrowError()
    {
        $return = $this->flashSession->getMessages('error');

        return implode(' ', $return);
    }

    public function checkLogin()
    {
        if (static::$userSession) {
            $this->redirectToUrl('/acp');
        }
    }
}
